﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using FSS.Core.Util;
using FSS.Core.Controls;
using FSS.BLL.Services;
using FSS.BLL.Entities;

namespace SalesManagement.Modules.Purchase
{
    public partial class VoucherInDetail : BasePage
    {
        public VoucherInDetail()
            : base(SCREENS.VOUCHERINDETAIL)
        {

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest && !IsPostBack)
            {
                if (Request["vcid"] != null)
                    hdDocumentID.Text = Request["vcid"].ToString();
            }

        }
        /// <summary>
        /// Khi load page success
        /// </summary>
        [DirectMethod]
        public void DocumentReady()
        {
            BindingProvider();
            BindingMaturity();
            BindingInputMethod();
            BindingEmployee();
            BindingCurency();
            BindingPaymentMethod();
            BindingUnit();
            BindingWaveHouse();
            BindingDocument();
            
        }
        private void BindingDocument()
        {
             Int64 VoucherInId = Format.ConvertToLong(hdDocumentID.Text);
                if (VoucherInId>0){
                    VoucherService service = VoucherService.GetInstance();
                    VoucherEntity resul = service.GetEntityByPrimaryKey(VoucherInId);
                    if (resul == null)
                        return;
                    txtVoucherNo.Text = resul.VoucherNo;
                    dfDocumentDate.SelectedDate =resul.VocherDate;
                    cbProvider.SelectedItem.Value = resul.ObjectId.ToString();
                    cbPaymentMethod.SelectedItem.Value=resul.PaymentMethodId.ToString();
                    cbMaturity.SelectedItem.Value= resul.MaturityId.ToString();
                    cbCurrency.SelectedItem.Value=resul.CurrencyId.ToString();
                    nfRate.SetValue(resul.CurrencyRate);
                    cbInputMethod.SelectedItem.Value=resul.InOutMethodId.ToString();
                    VoucherDetailService svDetail = VoucherDetailService.GetInstance();
                    IList<VoucherDetailEntity> lstDetail = svDetail.GetAllDetailByMasterID(VoucherInId);
                    stDetail.DataSource = lstDetail;
                    stDetail.DataBind();
                    btnNew.Disabled = false;
            }
            else
                    NewDataProcess();
          
        }
        /// <summary>
        /// Xóa dữ liệu cho thêm mới
        /// </summary>
        [DirectMethod]
        public bool NewDataProcess()
        {
            ConfigNumberService configNumberService = ConfigNumberService.GetInstance();
            txtVoucherNo.Text = configNumberService.GetNumberCode(Constants.VoucherType.PNK.ToString());
            dfDocumentDate.SelectedDate = DateTime.Now;
            txtAddress.Text = string.Empty;
            txtDocumentNo.Text = string.Empty;
            txtInvoiceNo.Text = string.Empty;
            txtTaxID.Text = string.Empty;
            List<VoucherDetailEntity> resul = new List<VoucherDetailEntity>();
            //for (int i = 1; i <= 10; i++)
            //{
            //    resul.Add(new VoucherInDetailEntity { VoucherInDetailId = i * -1 });
            //}
            //stDetail.DataSource = resul;
            stDetail.DataBind();
            btnNew.Disabled = true;
            return true;
        }
        #region HandleSave
        [DirectMethod]
        public bool SaveProcess(string JsonDetail)
        {
            try
            {
                VoucherEntity Voucher = getVoucherInEntity();
                VoucherService service = VoucherService.GetInstance();
                Int64 VoucherId = Format.ConvertToLong(hdDocumentID.Text);
                if (VoucherId>0)                
                    Voucher.VoucherId = VoucherId;
                VoucherId = service.InsertUpdate(Voucher);
                Voucher.VoucherType = Constants.VoucherType.PNK.ToString();
                if (VoucherId < 0)
                    return false;
                else hdDocumentID.Text = VoucherId.ToString();

                if (!string.IsNullOrEmpty(JsonDetail))
                {
                    string jsonGrouptOther = String.Format("{{{0}}}", JsonDetail);
                    jsonGrouptOther = jsonGrouptOther.Replace(",{}", "").Replace("[{}]", "");
                    StoreDataHandler dataGrouptOther = new StoreDataHandler(jsonGrouptOther);
                    ChangeRecords<VoucherDetailEntity> data = dataGrouptOther.ObjectData<VoucherDetailEntity>();
                    VoucherDetailService svDetail = VoucherDetailService.GetInstance();
                    foreach (VoucherDetailEntity ogroup in data.Updated)
                    {
                        ogroup.VoucherId = VoucherId;
                        ogroup.CreatedBy = 1;
                        ogroup.UpdatedBy = 1;                       
                        ogroup.UpdatedDate = DateTime.Now;
                        svDetail.InsertUpdate(ogroup);
                    }
                    foreach (VoucherDetailEntity ogroup in data.Created)
                    {
                        ogroup.VoucherId = VoucherId;
                        ogroup.CreatedDate = DateTime.Now;
                        svDetail.InsertUpdate(ogroup);
                    }
                    foreach (VoucherDetailEntity ogroup in data.Deleted)
                    {
                        svDetail.Delete(ogroup);
                    }
                }
                BindingDocument();
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private VoucherEntity getVoucherInEntity()
        {
            VoucherEntity Resul = new VoucherEntity();
            Resul.VoucherNo = txtVoucherNo.Text.Trim();
            if (dfDocumentDate.SelectedValue != null)
                Resul.VocherDate = dfDocumentDate.SelectedDate;
            else Resul.VocherDate = DateTime.Now;
            Resul.BranchId = 1;
            if (!string.IsNullOrEmpty(cbProvider.SelectedItem.Value))
                Resul.ObjectId= Format.ConvertToInt(cbProvider.SelectedItem.Value);
            if (!string.IsNullOrEmpty(cbPaymentMethod.SelectedItem.Value))
                Resul.PaymentMethodId = Format.ConvertToInt(cbPaymentMethod.SelectedItem.Value);
            if (!string.IsNullOrEmpty(cbMaturity.SelectedItem.Value))
                Resul.MaturityId = Format.ConvertToInt(cbMaturity.SelectedItem.Value);
            if (!string.IsNullOrEmpty(cbCurrency.SelectedItem.Value))
                Resul.CurrencyId = Format.ConvertToInt(cbCurrency.SelectedItem.Value);
            if (!string.IsNullOrEmpty(nfRate.Text))
                Resul.CurrencyRate = Format.ConvertToInt(nfRate.Value);
            if (!string.IsNullOrEmpty(cbInputMethod.SelectedItem.Value))
                Resul.InOutMethodId = Format.ConvertToInt(cbInputMethod.SelectedItem.Value);
            Resul.CreatedDate = DateTime.Now;
            Resul.CreatedBy = 1;
            Resul.UpdatedBy = 1;
            Resul.UpdatedDate = DateTime.Now;
            return Resul;
        }
        #endregion
        #region binding data
        /// <summary>
        /// Gan nha cung cap
        /// </summary>
        private void BindingProvider()
        {
            ObjectService service = ObjectService.GetInstance();
            IList<ObjectEntity> Resul = service.GetAllProvider();         
            stProvider.DataSource = Resul;
            stProvider.DataBind();
            if (Resul.Count > 0)
                cbProvider.SelectedIndex = 0;
        }
        /// <summary>
        /// Binding Han thanh toán
        /// </summary>
        private void BindingMaturity()
        {
            MaturityService service = MaturityService.GetInstance();
            IList<MaturityEntity> Resul = service.LoadAll();
     
            stMaturity.DataSource = Resul;
            stMaturity.DataBind();
            if (Resul.Count > 0)
                cbMaturity.SelectedIndex = 0;
        }
        private void BindingInputMethod()
        {
            InOutMethodService service = InOutMethodService.GetInstance();
            IList<InOutMethodEntity> Resul = service.LoadAll();
            stInputMethod.DataSource = Resul;
            stInputMethod.DataBind();
            if (Resul.Count > 0)
                cbInputMethod.SelectedIndex = 0;
        }
        private void BindingEmployee()
        {
            EmployeeService service = EmployeeService.GetInstance();
            IList<EmployeeEntity> Resul = service.LoadAll();
            if (Resul == null)
                return;
            stEmployee.DataSource = Resul;
            stEmployee.DataBind();
            if (Resul.Count > 0)
                cbEmployee.SelectedIndex = 0;
        }
        private void BindingCurency()
        {
            CurrencyService service = CurrencyService.GetInstance();
            IList<CurrencyEntity> Resul = service.LoadAll();
            if (Resul == null)
                return;
            stCurrency.DataSource = Resul;
            stCurrency.DataBind();
            if (Resul.Count > 0)
                cbCurrency.SelectedIndex = 0;
        }
        /// <summary>
        /// Binding Phuong thức thanh toán
        /// </summary>
        private void BindingPaymentMethod()
        {
            PaymentMethodService service = PaymentMethodService.GetInstance();
            IList<PaymentMethodEntity> Resul = service.LoadAll();
            if (Resul == null)
                return;
            stPaymentMethod.DataSource = Resul;
            stPaymentMethod.DataBind();
            if (Resul.Count > 0)
                cbPaymentMethod.SelectedIndex = 0;
        }
        /// <summary>
        /// Binding Đơn vị tính
        /// </summary>
        private void BindingUnit()
        {
            UnitService service = UnitService.GetInstance();
            IList<UnitEntity> Resul = service.LoadAll();
            if (Resul == null)
                return;
            stUnit.DataSource = Resul;
            stUnit.DataBind();
         
        }
        private void BindingWaveHouse()
        {
            WareHouseService service = WareHouseService.GetInstance();
            IList<WareHouseEntity> Resul = service.LoadAll();
            if (Resul == null)
                return;
            //stWareHouse.DataSource = Resul;
            //stWareHouse.DataBind();

        }
        

        #endregion      
    }
}
